<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info"
            show-icon />
        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: 'ID' + '/' + '分类名称' })" />
        <!-- 表格 -->
        <Table />

        <!-- 表单 -->
        <PopupForm />
    </div>
</template>

<script setup lang="ts">
import { provide, ref } from 'vue'
import baTableClass from '/@/utils/baTable'
import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
import { fullUrl } from '/@/utils/common'

defineOptions({
    name: 'goods/category',
})

const { t } = useI18n()

// 所有分类数据
const allCategories = ref<any[]>([])

// 按树形结构排序分类数据
const sortByTreeStructure = (items: any[]): any[] => {
    const itemMap: Record<number, any> = {}
    const rootItems: any[] = []
    const result: any[] = []

    // 构建ID到项目的映射
    items.forEach(item => {
        itemMap[item.id] = item
    })

    // 找出所有根节点（pid=0）
    items.forEach(item => {
        if (item.pid === 0) {
            rootItems.push(item)
        }
    })

    // 递归构建树状结构
    const buildTree = (parentItems: any[], level = 0) => {
        parentItems.forEach(parent => {
            // 添加到结果中
            result.push(parent)

            // 找出所有子节点
            const children = items.filter(item => item.pid === parent.id)
            if (children.length > 0) {
                buildTree(children, level + 1)
            }
        })
    }

    // 从根节点开始构建树
    buildTree(rootItems)

    return result
}

// 处理分类数据，直接修改name字段显示带缩进的分类名称，并处理图片路径
const processCategoryData = (items: any[]) => {
    // 先按树形结构排序
    let sortedItems = sortByTreeStructure(items)

    // 创建ID到层级的映射
    const levelMap: Record<number, number> = {}

    // 计算每个分类的层级
    const calculateLevel = (item: any, level = 0) => {
        levelMap[item.id] = level
        const children = items.filter(child => child.pid === item.id)
        children.forEach(child => calculateLevel(child, level + 1))
    }

    // 为根节点计算层级
    items.filter(item => item.pid === 0).forEach(root => calculateLevel(root))

    sortedItems = sortedItems.map(item => {
        // 克隆原始对象
        const processedItem = { ...item }

        // 保存原始名称，用于搜索等操作
        processedItem.originalName = item.name

        // 根据层级添加适当的缩进
        const level = levelMap[item.id] || 0
        if (level === 0) {
            // 顶级分类，保持原始名称
            processedItem.name = item.name
        } else {
            // 子分类，根据层级添加缩进前缀
            const indent = '　'.repeat(level)
            processedItem.name = indent + '└─ ' + item.name
        }

        // 处理图片路径，使用fullUrl函数确保路径正确
        if (processedItem.image) {
            processedItem.image = fullUrl(processedItem.image)
        }
        if (processedItem.big_image) {
            processedItem.big_image = fullUrl(processedItem.big_image)
        }

        return processedItem
    })
    return sortedItems
}

const baTable = new baTableClass(
    new baTableApi('/goods/category/'),
    {
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('Id'), prop: 'id', align: 'center', operator: '=', operatorPlaceholder: t('Id'), width: 70 },
            {
                label: '分类名称',
                prop: 'name', // 直接使用name字段，确保能正确显示
                align: 'left', // 左侧对齐更适合展示树形结构
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            { label: '图标', prop: 'image', align: 'center', render: 'image', operatorPlaceholder: t('Fuzzy query') },
            { label: '图片', prop: 'big_image', align: 'center', render: 'image', operator: false },
            { label: '权重', prop: 'weight', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            {
                label: '状态',
                prop: 'status',
                align: 'center',
                render: 'tag',
                custom: { 0: 'danger', 1: 'success' },
                replaceValue: { 0: t('隐藏'), 1: t('正常') },
            },
            { label: '创建时间', prop: 'createtime', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            { label: '更新时间', prop: 'update_time', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            {
                label: '操作',
                align: 'center',
                width: '100',
                render: 'buttons',
                buttons: defaultOptButtons(['edit', 'delete']),
                operator: false,
            },
        ],
        filter: {
            page: 1,
            limit: 999, // 一次性获取所有数据
        },
        dblClickNotEditColumn: [undefined],
    },
    {
        defaultItems: {
            weight: 0,
            status: 1,
            pid: 0,
        }
    },
    {},
    {
        getData: (args: any) => {
            const res = args.res
            if (res && res.code === 1 && res.data && res.data.rows && res.data.rows.length > 0) {
                // 保存所有分类数据
                allCategories.value = res.data.rows

                // 处理分类数据，直接修改name字段
                const processedData = processCategoryData(res.data.rows)

                // 更新数据
                res.data.rows = processedData
                res.data.total = processedData.length

                // 直接修改baTable.table中的数据，确保表格显示处理后的数据
                if (baTable && baTable.table) {
                    baTable.table.data = processedData
                    baTable.table.total = processedData.length
                }
            }
            return res
        },
        // 处理表单提交成功后的逻辑
        afterSubmit: (res: any) => {
            // 如果提交成功，重新获取数据以更新列表
            if (res && res.code === 1) {
                // 延迟刷新，确保后端已更新数据
                setTimeout(() => {
                    baTable.getData()
                }, 300)
            }
            return res
        },
        // 处理添加操作前的逻辑
        beforeAdd: () => {
            // 重置表单数据为默认值
            baTable.form.items = {
                ...baTable.form.defaultItems,
                name: '',
                intro: '',
                image: '',
                big_image: '',
                weight: 0,
                parent_id: 0,
                status: 1,
            }
            return true
        },
        // 处理编辑操作前的逻辑
        beforeEdit: (item: any) => {
            // 使用原始数据（不包含缩进前缀）填充表单
            if (item) {
                // 查找原始数据（未处理缩进的数据）
                const originalItem = allCategories.value.find(cat => cat.id === item.id)
                if (originalItem) {
                    // 复制原始数据到表单，确保字段映射正确
                    baTable.form.items = {
                        ...originalItem,
                        parent_id: originalItem.pid || 0,
                        intro: originalItem.intro || '',
                        weight: originalItem.weight || 0,
                    }
                } else {
                    // 如果找不到原始数据，使用当前项
                    baTable.form.items = {
                        ...item,
                        parent_id: item.pid || 0,
                        intro: item.intro || '',
                        weight: item.weight || 0,
                    }
                }
            }
            return true
        },

        getEditData({ res }) {
            console.log('getEditData', res)
            if (res.data) {
                baTable.form.items = res.data
            }
            if (!baTable.form.items.icon) {
                baTable.form.items.icon = 'fa fa-circle-o'
            }
            if (!baTable.form.items.menutype) {
                baTable.form.items.menutype = 'addtabs'
            }
        }
    }
)

// 重写auth方法，绕过权限控制，始终返回true
baTable.auth = function () {
    return true
}

baTable.mount()
baTable.getData()

// 提供baTable实例和分类数据
provide('baTable', baTable)
provide('allCategories', allCategories)
</script>

<style scoped lang="scss">
/* 确保树形结构显示美观 */
.ba-table-box {
    .el-table .cell {
        white-space: nowrap;
    }
}
</style>
